<template>
	<div class="container">
		<div class="header">
			<el-card>
				角色管理
			</el-card>
		</div>
		<!-- 用户列表 -->
		<div class="mian-table">
			<div style="padding: 20px 20px 0 20px;">
				<el-button @click="addUserInfor()" size=mini type="primary" icon="el-icon-plus">新增</el-button>
				<!-- 这里 -->
				<el-drawer :title="type === 0 ? '新增角色信息' : '修改角色信息'" :visible.sync="drawer" :direction="direction"
					:before-close="cancel">
					<el-form :model="form" :rules="rules" ref="form" label-position="top" label-width="80px">
						<el-form-item prop="name" style="padding-left: 20px;" label="请输入角色名称">
							<el-input style="width: 300px;" v-model="form.name" placeholder="请输入角色名称"></el-input>
						</el-form-item>
						<!-- 新增 -->
						<el-form-item v-if="type === 0" style="padding-left: 20px;" label="请选择权限">
							<div v-for="(item, i) in routesList" :key="i">
								<el-checkbox v-for="(val, i) in item.children" v-model="val.meta.checked">{{
                                    val.meta.title }}</el-checkbox>
							</div>
						</el-form-item>
						<!-- 修改 -->
						<el-form-item v-else style="padding-left: 20px;" label="请选择权限">
							<div v-for="(item, i) in form.content[0].children" :key="i">
								<el-checkbox v-model="item.checked">{{
                                    item.title }}</el-checkbox>
							</div>
						</el-form-item>
						<div class="add-drawer-btn">
							<el-button type="primary"
								@click="addRoleInfor(form)">{{ type === 0 ? '新增' : '修改' }}</el-button>
							<el-button @click="cancel">取消</el-button>
						</div>
					</el-form>
				</el-drawer>
			</div>
			<div style="margin: 20px">
				<el-table :data="tableData" height="600px" border
					style="width: 100%;margin-top: 10px;margin-bottom: 10px;">
					<template v-for="(val, index) in columns">
						<el-table-column align="center" :label="val.title" :key="index" :prop="val.dataKey">
						</el-table-column>
					</template>
					<el-table-column label="操作" align="center">
						<template slot-scope="scope" align="center">
							<el-button @click="updateRoleInfor(scope.row)" size="mini" type="text">修改</el-button>
							<el-divider direction="vertical"></el-divider>
							<el-button @click="deleteRoleInfor(scope.row)" slot="reference" size="mini" type="text"
								style="color: #F56C6C;">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</div>
		<div class="footer">
			<!-- <el-pagination align="center" background @size-change="handleSizeChange"
                @current-change="handleCurrentChange" :current-page.sync="form.pageNo"
                :page-size="form.pageSize" :page-sizes="[1, 10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper" :total="tableData.length">
            </el-pagination> -->
		</div>
	</div>
</template>
<script>
	import {
		getRoleList,
		addRole,
		updateRole,
		deleteRole
	} from "@/api/roleMangement.js";
	import {
		arrToObj
	} from '@/utils/arrToObj'
	export default {
		data() {
			return {
				type: 0,
				olderContent: [],
				checked: false,
				routesList: [],
				ruleForm: {
					name: '',
					username: '',
					pwd: '',
					quanxianid: 10,
				},
				currentPage: 1,
				pageSize: 1,
				rules: {
					name: [{
						required: true,
						message: '请输入用户名',
						trigger: 'blur'
					}, ]
				},
				drawer: false,
				direction: 'rtl',
				form: {
					name: '',
					content: [],
					adminid: Number(localStorage.getItem('userId'))
				},
				tableData: [],
				columns: [{
					dataKey: 'name',
					title: '角色名称',
				}],
			}
		},
		beforeMount() {
			this.getList()
			this.routesList = this.$router.options.routes
		},
		methods: {
			// 获取用户列表
			async getList() {
				this.loading = true
				let arr = await getRoleList({
					adminid: Number(localStorage.getItem('userId'))
				})
				if (arr.code == 0 && arr.data.length !== 0) {
					this.tableData = arr.data
					this.loading = false
				}

			},
			handleSizeChange(size) {
				this.form.pageSize = size;
				this.getList();
			},
			//当前页改变时触发 跳转其他页
			handleCurrentChange(currentPage) {
				this.form.pageNo = currentPage;
				this.getList();
			},
			// 关闭抽屉
			handleClose() {
				this.drawer = false
			},
			// 新增用户
			addUserInfor() {
				this.drawer = true
				this.type = 0
				this.form = {
					name: '',
					content: []
				}
			},
			// 取消
			cancel() {
				this.drawer = false
				if (this.type === 0) {
					this.form.name = ''
					this.routesList.forEach(item => {
						if (item.children !== undefined) {
							if (item.children[0].meta.checked && item.children[0].meta.checked === true) {
								item.children[0].meta.checked = false
							}
							// item.children[0].meta.checked=false
						}
					})
				} else {
					console.log(this.form.content[0].children);
				}
			},
			// 修改用户
			async updateRoleInfor(row) {
				this.drawer = true
				this.type = 1
				this.form.id = row.id
				const arr = await getRoleList();
				console.log('row', row)
				
				
				const obj = arr.data.find(item => item.id === row.id)
				
				console.log('这是obj',obj);
				let list =  JSON.parse(obj.content);
				
				for (var i = 0; i < list.length; i++) {
					console.log('arr循环', list[i])
				}
		


				if (typeof obj.content === 'string') {
					this.form.content = JSON.parse(obj.content)
					this.form.name = obj.name
				}
			},
			// 删除用户
			deleteRoleInfor(row) {
				this.$confirm('确定要删除吗？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					deleteRole({
						id: row.id,
						adminid: Number(localStorage.getItem('userId'))
					}).then(res => {
						if (res.code === 0) {
							this.$message.success("删除成功!");
							this.getList()
						} else {
							this.$message.success("删除失败", res.error);
						}
					})
				}).catch(() => {});
			},
			// 新增/修改用户提交
			addRoleInfor(form) {
				this.$refs.form.validate((valid) => {
					if (valid) {
						if (this.type == 0) {
							var obj = {
								children: []
							}
							this.routesList.forEach(item => {
								if (item.children !== null && item.children !== undefined) {
									item.children.forEach((val, index) => {
										obj.path = item.path
										val.meta.path = item.path
										val.meta.meta = {
											path: val.meta.path,
											title: val.meta.title,
											icon: val.meta.icon
										}
										obj.children.push(val.meta)
									})

								}

							})
							this.form.content.push(obj)
						}
						if (this.type === 1) {
							this.form.content = JSON.stringify(this.form.content)
							this.form.adminid = Number(localStorage.getItem('userId'))
							updateRole(this.form).then(res => {
								if (res.code === 0) {
									this.$message.success("修改成功!");
									this.drawer = false
									this.getList()
									this.cancel()
								} else {
									this.$message.success("修改失败", res.error);
								}
							})
						} else {
							this.form.content = JSON.stringify(this.form.content)
							this.form.adminid = Number(localStorage.getItem('userId'))
							addRole(this.form).then(res => {
								if (res.code === 0) {
									this.$message.success("新增成功!");
									this.drawer = false
									this.getList()
									this.cancel()
								} else {
									this.$message.success("新增失败", res.error);
								}
							})
						}
					} else {
						return false
					}
				})
			}
		},
	}
</script>
<style style="scss" scoped>
	.header {
		font-size: 18px;
		font-weight: 400
	}

	.container {
		background-color: #EBEEF5
	}

	.mian-table {
		height: 693px;
		margin: 20px;
		background-color: white;

		.add-drawer-btn {
			padding: 20px 0 20px 20px;
			position: absolute;
			bottom: 0;
			right: 5%;
			text-align: right
		}

		.form-item {
			width: 250px;
		}
	}

	.footer {
		height: 3%;
		background-color: white;
		/* text-align: center; */
		padding: 20px
	}
</style>